# -*- coding: utf-8 -*-

from src.ucloud.ufile_config import read_config
from lib.ucloud.ufile import deleteufile
from twisted.internet import reactor
from src.db.query_ucloud_db import read_list
from src.db.ucloud_db import update_item, delete_item
from src.sshconn.ssh_conn import singleton
from multiprocessing.dummy import Pool as ThreadPool
from lib.ucloud.logger import logger


@singleton
class DeleteFile(object):

    def __init__(self):
        public_key, private_key, bucket = read_config()

        self.bucket = bucket
        # 构造对象，并设置公私钥
        self.handler = deleteufile.DeleteUFile(public_key, private_key)
        self.index = 0
        self.pool = ThreadPool(500)  # 1000是线程池中线程的个数

    def delete_file(self):
        while True:
            # 读记录
            log_list = read_list({'download_state': 2, 'offset': self.index*500, 'count': 500})
            if log_list is None or len(log_list) <= 0:
                break
            self.index = self.index + 1
            # 线程池 异步删除
            self.pool.map(self.delete_item, log_list)
        logger.info("delete end")
        # reactor.stop()

    def delete_item(self, item):
        # 删除公共空间的文件
        ret, resp = self.handler.deletefile(self.bucket, item.get('FileName', ''))
        if resp.status_code == 204:
            # 删除成功 修改库记录
            item['download_state'] = 3
            # update_item(item)
            delete_item(item)
        # else:
            # 删除失败 修改库记录
            # item['download_state'] = 4
            # update_item(item)


if __name__ == "__main__":
    reactor.callWhenRunning(DeleteFile().delete_file)
    reactor.run()
